package com.study.business.record.service;

import com.study.business.record.domain.Record;
import com.study.business.record.mapper.RecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/********************************************
 * @author: zhang
 * @Description: com.huawei.core.service
 * @Date: 下午 9:21 2018/7/4 0004
 * @Modified By:
 ********************************************/
@Service
public class RecordService {

    @Autowired
    private RecordMapper recordMapper;

    public List<Record> getAll() {
        List<Record> categories = recordMapper.selectCategory();
        List<Record> records = recordMapper.selectRecord();
        System.out.println(categories);
        System.out.println(records);
        return generateTree(null, categories, records);
    }

    private List<Record> generateTree(String categoryID, List<Record> categories, List<Record> records) {
        List<Record> recordTree = new ArrayList<>();
        for (Record category : categories) {
            if (categoryID == null && category.getParentID() == null) {
                category.setType("dir");
                category.setChild(generateTree(category.getCategoryID(), categories, records));
                recordTree.add(category);
            }

            if (categoryID != null && categoryID.equals(category.getParentID())) {
                category.setType("dir");
                category.setChild(generateTree(category.getCategoryID(), categories, records));
                recordTree.add(category);
            }

        }

        for (Record record : records) {
            if (categoryID == null && record.getCategoryID() == null) {
                record.setType("file");
                recordTree.add(record);
            }

            if (categoryID != null && categoryID.equals(record.getCategoryID())) {
                record.setType("file");
                recordTree.add(record);
            }
        }
        return recordTree.size() == 0 ? null : recordTree;
    }
}
